using System;
using System.Collections.Generic;
using TddGenerator.Core.Domain;
using TddGenerator.Core.Services;

namespace TddGenerator.Ui
{
    public class InterfaceUnderTestSelectorPresenter
    {
        private readonly IDefaultSettingsRepository defaults;
        private readonly IClassGenerator generator;
        private readonly IProjectRepository repository;
        private readonly IInterfaceUnderTestSelectorView view;

        public InterfaceUnderTestSelectorPresenter(IProjectRepository repository, IInterfaceUnderTestSelectorView view,
                                                   IClassGenerator generator, IDefaultSettingsRepository defaults)
        {
            this.repository = repository;
            this.view = view;
            this.generator = generator;
            this.defaults = defaults;
        }

        public void view_EscPressed(object sender, EventArgs e)
        {
            view_CancelButtonClicked(sender, e);
        }

        public void view_EnterPressed(object sender, EventArgs e)
        {
            view_OkButtonClicked(sender, e);
        }

        public void view_OkButtonClicked(object sender, EventArgs e)
        {
            ClassToCreate classToCreate = new ClassToCreate();

            classToCreate.ClassProject = view.ClassProjectName;
            classToCreate.TestProject = view.TestProjectName;
            classToCreate.FolderHierarchy = view.FolderName;
            classToCreate.ClassName = view.ClassName;
            this.defaults.Save(new DefaultSettings()
            {
                ClassProject = classToCreate.ClassProject,
                TestProject = classToCreate.TestProject,
                Namespace = string.Join(".",new List<string>( classToCreate.FolderHierarchy).ToArray())
            }
        );
            generator.CreateClasses(classToCreate);
            view.Close();
        }

        public void view_CancelButtonClicked(object sender, EventArgs e)
        {
            view.Close();
        }

        public void Load()
        {
            view.CancelButtonClicked += new EventHandler(view_CancelButtonClicked);
            view.OkButtonClicked += new EventHandler(view_OkButtonClicked);
            view.EnterPressed += new EventHandler(view_EnterPressed);
            view.EscPressed += new EventHandler(view_EscPressed);

            view.SetClassProjectDropdown(repository.GetProjectNames());
            view.SetTestProjectDropdown(repository.GetProjectNames());

            DefaultSettings settings = defaults.Get();
            if (settings != null)
            {
                view.SetClassProjectText(settings.ClassProject);
                view.SetTestProjectText(settings.TestProject);
                view.SetFolder(settings.Namespace);
            }
            view.Show();
        }
    }
}